// plugins/v-counter.js
export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.directive('counter', {
        updated(el, binding) {
            console.log('updated', el, binding)
            el.cur = binding.oldValue
            el.targetNum = binding.value
            el.timer = setInterval(el.jump, 50)
        },
        beforeMount(el, binding) {
            el.jump = () => {
                let step = Math.ceil((el.targetNum - el.cur) / 5)
                el.cur = Math.round(el.cur + step)
                if (Math.abs(el.targetNum - el.cur) < 1) {
                    el.innerText = el.targetNum
                    clearInterval(el.timer)
                    return
                }
                el.innerText = el.cur
            }
        },
        mounted(el, binding) {
            el.cur = 0
            el.targetNum = Number(binding.value)
            el.timer = setInterval(el.jump, 50)
            el.innerText = el.cur
        },
        unmounted(el) {
            el.jump = null
            clearInterval(el.timer)
        }
    })
})

// 移除元素
// const removeEl = (el) => el.parentNode && el.parentNode.removeChild(el);